package com.ardf.listener;

import com.ardf.entity.Card;
import com.ardf.entity.dto.CardDto;
import com.ardf.entity.dto.CardSearchAllDto;
import com.ardf.entity.dto.ReplaceCardTableDto;
import com.ardf.service.CardWebSocketService;
import com.ardf.service.IAthleteService;
import com.ardf.service.ICardService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import org.springframework.web.socket.WebSocketSession;

import java.util.Arrays;
import java.util.List;

public class ReplacePortListener implements SerialPortDataListener {

    private CardWebSocketService webSocketService;
    private ICardService cardService;

    private IAthleteService athleteService;
    private WebSocketSession session;
    private String portName;
    private Long competitionId;
    private Long athleteId;



    private int GetTen(int num1, int num2) {
        return (num1 / 16) * 16 * 16 * 16 + (num1 % 16) * 16 * 16 + num2;
    }

    private Long GetTPNumber(int[] intArray) {
        double TpNumber=0;
        for (int i = 0; i < intArray.length; i++) {
            TpNumber+=Math.pow(16,7-i*2) * (intArray[i] /16) + Math.pow(16,7-i*2-1) * (intArray[i] %16);

        }
        return (long) TpNumber;
    }

    //通过websocket打开监听设备的时候绑定session返回给前端数据
    public ReplacePortListener(CardWebSocketService webSocketService, String portName, WebSocketSession session, ICardService cardService,IAthleteService athleteService,Long competitionId,Long athleteId) {
        this.webSocketService=webSocketService;
        this.cardService=cardService;
        this.athleteService=athleteService;
        this.portName = portName;
        this.session = session;
        this.competitionId=competitionId;
        this.athleteId=athleteId;
    }

    @Override
    public int getListeningEvents() {

        return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
    }

    @Override
    public void serialEvent(SerialPortEvent event) {
        boolean flag=true;
        SerialPort port = event.getSerialPort();  //获取当前的com口
        this.webSocketService.sendMessageToUser(this.competitionId,"请放置指卡");


        if (event.getEventType() == SerialPort.LISTENING_EVENT_DATA_AVAILABLE) {//如果此时没有数据进来则退出监听器
            this.webSocketService.sendMessageToUser(this.competitionId,"读卡中......");
            while(port.bytesAvailable()!=0){

                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                byte[] newData = new byte[port.bytesAvailable()];//会返回字符数
                int[] intArray = new int[port.bytesAvailable()];
                int i = 0;
                int numRead = port.readBytes(newData, newData.length); //数据长度
                for (byte data : newData) {
                    System.out.print((data & 0xFF) + " ");
                    intArray[i] = (data & 0xFF);
                    i++;
                }

                //获取到TP卡号
                String TPCard= "TP" + GetTPNumber(Arrays.copyOfRange(intArray,14,18));
                //判断当前赛事是否存在此卡
                if(this.cardService.selectByComAndNum(this.competitionId,TPCard)){
                    CardDto card=new CardDto(null,TPCard,this.athleteId,this.competitionId);
                    this.cardService.insertTPCard(card);
                    flag=true;
                }else{
                    flag=false;
                }

                try {
                    if(flag){
                        Thread.sleep(500);
                        System.out.println();
                        this.webSocketService.sendMessageToUser(this.competitionId,"读卡结束......");
                        Thread.sleep(500);
                        this.webSocketService.sendMessageToUser(this.competitionId,"请放置指卡");
                    }else{
                        Thread.sleep(1000);
                        this.webSocketService.sendMessageToUser(this.competitionId,"该卡已经存在，请换卡！！！");
                    }

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }

}
